# coding=utf-8
import os
import queue
import threading
import time

import numpy as np
import requests

url = ""

time_collector = []
rst = queue.Queue()  # 线程编号,第几次下载,耗时,文件大小


def download_file(filename):
    start = int(round(time.time() * 1000))
    print('start to download: %d, start: %d' % (filename, start))
    try:
        resp = requests.get(url)
        d_dir = os.path.join(os.path.dirname(os.path.abspath("__file__")), 'download')
        if not os.path.exists(d_dir):
            os.makedirs(d_dir)
        file_path = os.path.join(d_dir, '%d.pkg' % filename)
        if os.path.exists(file_path):
            os.remove(file_path)
        with open(file_path, "wb") as f:
            f.write(resp.content)
        cost = int(round(time.time() * 1000)) - start
        time_collector.append(cost)
        print('%d download cost: %d ms' % (filename, cost))
        return cost, os.path.getsize(file_path)
    except Exception as e:
        print('error happen :', e)
        return -1, -1


def start_thread(filename, end_time):
    # cost, size = download_file(filename)
    # rst.put('%s,%s,%s,%s\n' % (filename, 1, cost, size))
    count = 0
    while True:
        count += 1
        cur_time = int(round(time.time() * 1000))
        if cur_time > end_time:
            break
        print('%d next start, count: %d.' % (filename, count))
        cost, size = download_file(filename)
        rst.put('%s,%s,%s,%s\n' % (filename, count, cost, size))


def write_rst():
    tmp = []
    while True:
        while rst.qsize() > 0:
            tmp.append(rst.get())
        if len(tmp) > 0:
            with open(os.path.join(os.path.dirname(os.path.abspath("__file__")), 'rst.csv'), 'a') as wf:
                wf.writelines(tmp)
            tmp = []
        time.sleep(10)


def start_download(thread_num, end_time):
    # executor = ThreadPoolExecutor(max_workers=thread_num + 1)
    t = []
    for i in range(thread_num):
        # t.append(executor.submit(start_thread, i, end_time))
        new = threading.Thread(target=start_thread, args=(i, end_time), daemon=True)
        t.append(new)
        new.start()
    threading.Thread(target=write_rst, daemon=True).start()

    stop = False
    while not stop:
        cur_time = int(round(time.time() * 1000))
        if cur_time > end_time:
            time.sleep(5 * 60)
            break
        stop = True
        for item in t:
            if item.is_alive():
                stop = False
        time.sleep(20)
    print('download end...')


def print_time_index():
    if len(time_collector) > 0:
        max_t, min_t = time_collector[0], time_collector[0]
        avg = np.mean(time_collector)
        # 离散程度
        var = np.var(time_collector)
        std = np.std(time_collector, ddof=1)  # 方差的平方根
        for item in time_collector:
            max_t = max(max_t, item)
            min_t = min(min_t, item)

        print('time index: 平均值: %s, 方差：%s, 标准差：%s, 最大值：%s, 最小值：%s' % (avg, var, std, max_t, min_t))
        print('time details:', time_collector)
    print('no time msg....')


if __name__ == '__main__':
    # 下载时长
    duration = 24 * 60  # min
    # 同时下载线程数
    th_num = 50
    # 设置压测url
    # url = "http://47.98.158.184/fota-version/download/general/update.pkg?" \
    #       "product=pressure_test&imei=123&old_version=pressure_test_1&new_version=pressure_test_2&auto=0"
    url = 'http://120.55.39.193/fota-version/download/general/update.pkg?product=aaa&imei=123&old_version=v00&new_version=v1&auto=0'
    # 开始测试
    start_download(th_num, int(round(time.time() * 1000)) + duration * 60 * 1000)
    print_time_index()
